//
//  SearchController.m
//  YiBaoStore
//
//  Created by 毛云河 on 2018/10/8.
//  Copyright © 2018年 小河. All rights reserved.
//

#import "SearchController.h"
#import "SearchHisCell.h"

#define PYMargin 15 // 默认边距
#define PYSEARCH_SEARCH_HISTORY_CACHE_PATH [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"SearchHistor.plist"] // 搜索历史存储路径


@interface SearchController ()<UITableViewDelegate,UITableViewDataSource>

/** 基本搜索TableView(显示历史搜索和搜索记录) */
@property (nonatomic, strong) UITableView *baseSearchTableView;
//搜索框
@property (nonatomic, strong) UITextField *searchTF;
//表头view
@property (nonatomic, strong) UIView *headerView;
//热门搜索view
@property (nonatomic, strong) UIView *hotSearchView;
//历史搜索view
@property (nonatomic, strong) UIView *hisSearchView;

/** 搜索历史 */
@property (nonatomic, strong) NSMutableArray *searchHistories;
/** 搜索历史缓存保存路径, 默认为PYSEARCH_SEARCH_HISTORY_CACHE_PATH(PYSearchConst.h文件中的宏定义) */
@property (nonatomic, copy) NSString *searchHistoriesCachePath;
/** 搜索历史记录缓存数量，默认为20 */
@property (nonatomic, assign) NSUInteger searchHistoriesCount;

@end

@implementation SearchController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.searchHistoriesCount = 20;
    //1,创建搜索视图
    [self createSearchView];
    
    NSString *itemState = USER_DEFAULTS_GET(@"itemState");
    if (IsEmptyStr(itemState))
    {//平台进来有热词
        //2,请求热词数据
        [self httpReuqestHotWords];
    }
}

- (NSMutableArray *)searchHistories
{
    if (!_searchHistories)
    {
        self.searchHistoriesCachePath = PYSEARCH_SEARCH_HISTORY_CACHE_PATH;
        _searchHistories = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:self.searchHistoriesCachePath]];
    }
    return _searchHistories;
}

#pragma mark - 请求热词数据
- (void)httpReuqestHotWords
{
    __weak SearchController *myself = self;
    [[HttpRequest currentHttpRequest] postPath:HotWords_API params:nil resultBlock:^(NSArray *Data, MsgModel *msgModel)
    {
        NSLog(@"热词--%@",Data);
        [myself addAndLayoutTagsWithTagsContentView:myself.hotSearchView tagTexts:Data];
    }];
}
    
#pragma mark - 懒加载
- (UITableView *)baseSearchTableView
{
    if (!_baseSearchTableView)
    {
        UITableView *baseSearchTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        baseSearchTableView.backgroundColor = [UIColor whiteColor];
        baseSearchTableView.delegate = self;
        baseSearchTableView.dataSource = self;
        [self.view addSubview:baseSearchTableView];
        _baseSearchTableView = baseSearchTableView;
    }
    return _baseSearchTableView;
}

- (void)createSearchView
{
    self.baseSearchTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (@available(iOS 11.0, *)) {
        self.baseSearchTableView.frame = CGRectMake(0, TopBarHeight_xs, SCREENWIDTH, SCREENHEIGHT-TopBarHeight_xs);
    } else {
        // Fallback on earlier versions
        self.baseSearchTableView.frame = CGRectMake(0, TopBarHeight, SCREENWIDTH, SCREENHEIGHT-TopBarHeight);
    }
    [self.baseSearchTableView registerClass:[SearchHisCell class] forCellReuseIdentifier:@"SearchHisCell"];
    self.baseSearchTableView.tableHeaderView = [self createHeaderView];
}

- (UIView *)createHeaderView
{
    self.headerView = [[UIView alloc]init];
    self.headerView.backgroundColor = [UIColor whiteColor];
    
    //搜索标题
    UILabel *searchLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 13, 100, 33)];
    [self.headerView addSubview:searchLabel];
    searchLabel.text = @"搜索";
    searchLabel.textColor = BlackTextColor;
    searchLabel.font = FontMediumWithSize(24);
    searchLabel.textAlignment = 0;
    
    //搜索框
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.headerView addSubview:searchBtn];
    searchBtn.frame = CGRectMake(SCREENWIDTH-15-40, searchLabel.bottom+5, 40, 40);
    [searchBtn addTarget:self action:@selector(searchBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *searchIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sear_shopping"]];
    [self.headerView addSubview:searchIcon];
    searchIcon.frame = CGRectMake(SCREENWIDTH-15-18, searchLabel.bottom+11, 18, 18);
    
    self.searchTF = [[UITextField alloc] init];
    [self.headerView addSubview:self.searchTF];
    self.searchTF.frame = CGRectMake(15, searchLabel.bottom+5, SCREENWIDTH-30-40, 40);
    self.searchTF.font = FontWithSize(14);
    self.searchTF.placeholder = @"请输入商品名称";
    
    //分割线
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(15, searchLabel.bottom+45, SCREENWIDTH-30, 1)];
    [self.headerView addSubview:lineView];
    lineView.backgroundColor = BtnBgColor;
    
    NSString *itemState = USER_DEFAULTS_GET(@"itemState");
    if (IsEmptyStr(itemState))
    {//平台进来有热词
        //热门搜索
        UILabel *hotSearchTit = [[UILabel alloc] initWithFrame:CGRectMake(15, lineView.bottom+20, 100, 20)];
        [self.headerView addSubview:hotSearchTit];
        hotSearchTit.text = @"热门搜索";
        hotSearchTit.textColor = RGBACOLOR(167, 166, 166, 1);
        hotSearchTit.font = FontWithSize(14);
        
        //    UIButton *changBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        //    [self.headerView addSubview:changBtn];
        //    changBtn.frame = CGRectMake(SCREENWIDTH-42-15, hotSearchTit.top, 42, 20);
        //    changBtn.titleLabel.font = FontWithSize(14);
        //    [changBtn setTitle:@"换一批" forState:UIControlStateNormal];
        //    [changBtn setTitleColor:BtnBgColor forState:UIControlStateNormal];
        //    [changBtn addTarget:self action:@selector(changBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        //热门搜索bgView
        self.hotSearchView = [[UIView alloc] init];
        [self.headerView addSubview:self.hotSearchView];
        self.hotSearchView.frame = CGRectMake(0, hotSearchTit.bottom+30, SCREENWIDTH, 0);
        
        //历史搜索title
        self.hisSearchView = [[UIView alloc] init];
        [self.headerView addSubview:self.hisSearchView];
        self.hisSearchView.frame = CGRectMake(0, self.hotSearchView.bottom+30, SCREENWIDTH, 20);
        
        UILabel *hisSearchTit = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 20)];
        [self.hisSearchView addSubview:hisSearchTit];
        hisSearchTit.text = @"搜索历史";
        hisSearchTit.textColor = RGBACOLOR(167, 166, 166, 1);
        hisSearchTit.font = FontWithSize(14);
        
        UIButton *cleanBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [self.hisSearchView addSubview:cleanBtn];
        cleanBtn.frame = CGRectMake(SCREENWIDTH-56-15, hisSearchTit.top, 56, 20);
        cleanBtn.titleLabel.font = FontWithSize(14);
        [cleanBtn setTitle:@"清除历史" forState:UIControlStateNormal];
        [cleanBtn setTitleColor:BtnBgColor forState:UIControlStateNormal];
        [cleanBtn addTarget:self action:@selector(cleanBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        self.headerView.frame = CGRectMake(0, 0, SCREENWIDTH, hisSearchTit.bottom+5);
    }
    else {
        //自营进来没有热词
        //历史搜索title
        self.hisSearchView = [[UIView alloc] init];
        [self.headerView addSubview:self.hisSearchView];
        self.hisSearchView.frame = CGRectMake(0, lineView.bottom+20, SCREENWIDTH, 20);
        
        UILabel *hisSearchTit = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 20)];
        [self.hisSearchView addSubview:hisSearchTit];
        hisSearchTit.text = @"搜索历史";
        hisSearchTit.textColor = RGBACOLOR(167, 166, 166, 1);
        hisSearchTit.font = FontWithSize(14);
        
        UIButton *cleanBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [self.hisSearchView addSubview:cleanBtn];
        cleanBtn.frame = CGRectMake(SCREENWIDTH-56-15, hisSearchTit.top, 56, 20);
        cleanBtn.titleLabel.font = FontWithSize(14);
        [cleanBtn setTitle:@"清除历史" forState:UIControlStateNormal];
        [cleanBtn setTitleColor:BtnBgColor forState:UIControlStateNormal];
        [cleanBtn addTarget:self action:@selector(cleanBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        self.headerView.frame = CGRectMake(0, 0, SCREENWIDTH, 140);
    }
    
    
    return self.headerView;
}

#pragma mark - 搜索按钮点击事件
- (void)searchBtnClick:(UIButton *)sender
{
    //1,保存搜索关键字
    if (IsEmptyStr(self.searchTF.text))
    {
        return;
    }
    [self saveSearchCacheAndRefreshView:self.searchTF.text];
    
    //2，前往商品搜索界面
    [self gotoSerachResultVCWithKeyword:self.searchTF.text];
}

#pragma mark - 换一批热门搜索
- (void)changBtnClick:(UIButton *)sender
{
    
}

#pragma mark - 清空历史记录
- (void)cleanBtnClick:(UIButton *)sender
{
    //1，隐藏历史搜索抬头
    self.hisSearchView.hidden = YES;
    //2，移除所有历史搜索
    [self.searchHistories removeAllObjects];
    //3，移除数据缓存
    [NSKeyedArchiver archiveRootObject:self.searchHistories toFile:self.searchHistoriesCachePath];
    //4，刷新表视图
    [self.baseSearchTableView reloadData];
}

#pragma mark - tableView的代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.searchHistories.count == 0)
    {
        self.hisSearchView.hidden = YES;
    }
    else {
        self.hisSearchView.hidden = NO;
    }
    return self.searchHistories.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchHisCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchHisCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.leftTitlte.text = self.searchHistories[indexPath.row];
    cell.closeBtn.indexPath = indexPath;
    [cell.closeBtn addTarget:self action:@selector(closeBtnDelegateHis:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //1，找到当前cell
    SearchHisCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    //2，前往搜索结果页
    [self gotoSerachResultVCWithKeyword:cell.leftTitlte.text];
}

/**  添加和布局标签 */
- (void)addAndLayoutTagsWithTagsContentView:(UIView *)contentView tagTexts:(NSArray<NSString *> *)tagTexts;
{
    // 清空标签容器的子控件
    [contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    // 添加热门搜索标签
    NSMutableArray *tagsM = [NSMutableArray array];
    for (int i = 0; i < tagTexts.count; i++)
    {
        UILabel *label = [self labelWithTitle:tagTexts[i]];
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tagDidCLick:)]];
        [contentView addSubview:label];
        [tagsM addObject:label];
    }
    
    // 计算位置
    CGFloat currentX = 15;
    CGFloat currentY = 0;
    CGFloat countRow = 0;
    CGFloat countCol = 0;
    
    // 调整布局
    for (UILabel *subView in tagsM) {
        // 当搜索字数过多，宽度为contentView的宽度
        if (subView.width > contentView.width) subView.width = contentView.width;
        
        if (currentX + subView.width + PYMargin * countRow > contentView.width)
        { // 得换行
            subView.left = 15;
            subView.top = (currentY += subView.height) + PYMargin * ++countCol;
            currentX = subView.width+15;
            countRow = 1;
        } else { // 不换行
            subView.left = (currentX += subView.width) - subView.width + PYMargin * countRow;
            subView.top = currentY + PYMargin * countCol;
            countRow ++;
        }
    }
    // 设置contentView高度
    contentView.height = CGRectGetMaxY(contentView.subviews.lastObject.frame);
    // 设置头部高度
    self.hisSearchView.frame = CGRectMake(0, contentView.bottom+30, SCREENWIDTH, 20);
    self.headerView.frame = CGRectMake(0, 0, SCREENWIDTH, self.hisSearchView.bottom+5);
    self.baseSearchTableView.tableHeaderView.height = self.headerView.height;
    [self.baseSearchTableView setTableHeaderView:self.baseSearchTableView.tableHeaderView];
}

/** 添加标签 */
- (UILabel *)labelWithTitle:(NSString *)title
{
    UILabel *label = [[UILabel alloc] init];
    label.userInteractionEnabled = YES;
    label.font = [UIFont systemFontOfSize:12];
    label.text = title;
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = RGBACOLOR(167, 166, 166, 1);
    label.backgroundColor = [UIColor whiteColor];
    label.layer.cornerRadius = 9;
    label.layer.masksToBounds = YES;
    label.layer.borderWidth = 1;
    label.layer.borderColor = RGBACOLOR(158, 158, 158, 0.3).CGColor;
    label.layer.shadowOffset = CGSizeMake(2, 2);
    label.layer.shadowColor = [UIColor blackColor].CGColor;
    [label sizeToFit];
    label.width += 24;
    label.height += 6;
    return label;
}

/** 选中标签 */
#pragma mark - 选中热门搜索标签
- (void)tagDidCLick:(UITapGestureRecognizer *)gr
{
    //1，取出热词
    UILabel *label = (UILabel *)gr.view;
    NSLog(@"热词--%@",label.text);
    //2，保存热词
    [self saveSearchCacheAndRefreshView:label.text];

    //3,返回前往商品搜索界面
    [self gotoSerachResultVCWithKeyword:label.text];
}

#pragma mark - 前往搜索结果页
- (void)gotoSerachResultVCWithKeyword:(NSString *)text
{
    SearchResultController *vc = [[SearchResultController alloc] init];
    vc.key_word = text;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 单个清楚搜索历史
- (void)closeBtnDelegateHis:(UIButton *)sender
{
    //1，取出当前cell
    SearchHisCell *cell = [self.baseSearchTableView cellForRowAtIndexPath:sender.indexPath];
    //2,移除当前cell的标题
    [self.searchHistories removeObject:cell.leftTitlte.text];
    //3，保存修改后的搜索信息
    [NSKeyedArchiver archiveRootObject:self.searchHistories toFile:PYSEARCH_SEARCH_HISTORY_CACHE_PATH];
    //4，判断历史搜索的抬头
    if (self.searchHistories.count == 0)
    {
        self.hisSearchView.hidden = YES;
    }
    else {
        self.hisSearchView.hidden = NO;
    }
    
    //5，刷新表
    [self.baseSearchTableView reloadData];
}

#pragma mark - 保存搜索关键字
- (void)saveSearchCacheAndRefreshView:(NSString *)searchText
{
    //1,回收键盘
    [self.searchTF resignFirstResponder];
    
    //2，先移除再插入刷新
    [self.searchHistories removeObject:searchText];
    [self.searchHistories insertObject:searchText atIndex:0];
    
    //3，当缓存大于20条的时候，移除最后一条缓存
    if (self.searchHistories.count > self.searchHistoriesCount)
    {
        // 移除最后一条缓存
        [self.searchHistories removeLastObject];
    }
    
    //4，保存搜索信息
    [NSKeyedArchiver archiveRootObject:self.searchHistories toFile:self.searchHistoriesCachePath];
    
    //5，刷新n表
    [self.baseSearchTableView reloadData];
}

@end
